import { getAllDictionary } from "@/api/dictionary";
import { AllDictionaryRecord, Response } from "@/typings/api";

let dictionaryReuestCache: Promise<Response<AllDictionaryRecord[]>> | null = null; // 并发调用getCacheDictionary时使用缓存请求

export const getCacheDictionary = async (): Promise<AllDictionaryRecord[]> => {
    const storedData = localStorage.allDictionary;
    if (storedData) return JSON.parse(storedData);
    if (!dictionaryReuestCache) dictionaryReuestCache = getAllDictionary();
    const { data } = await dictionaryReuestCache;
    dictionaryReuestCache = null;
    localStorage.allDictionary = JSON.stringify(data);
    return data;
};

export const getDictionaryData = async (key: string): Promise<AllDictionaryRecord["dictItems"]> => {
    const data = await getCacheDictionary();
    return data.find(item => item.key === key)?.dictItems || [];
};

export const getDictionaryLabel = async (key: string, value: string | boolean | number) => {
    const data = await getDictionaryData(key);
    if (typeof value === "boolean") return data.find(item => (item.value === "true" ? true : false) === value)?.label || "";
    if (typeof value === "number") return data.find(item => +item.value === value)?.label || "";
    return data.find(item => item.value === value)?.label || "";
};

export const getDictionaryBackgroundColor = async (key: string, value: string | boolean | number) => {
    const data = await getDictionaryData(key);
    if (typeof value === "boolean") return data.find(item => (item.value === "true" ? true : false) === value)?.backgroundColor || "";
    if (typeof value === "number") return data.find(item => +item.value === value)?.backgroundColor || "";
    return data.find(item => item.value === value)?.backgroundColor || "";
};
